<?php

namespace app\install;

use app\admin\model\Site;
use app\admin\services\SitesServices;
use InvalidArgumentException;
use plugin\admin\api\Menu;
use plugin\admin\app\common\Util;
use plugin\cron\api\Install as CrontabInstall;
use plugin\email\api\Install as EmailInstall;
use plugin\sms\api\Install as SmsInstall;
use RuntimeException;
use Throwable;

/**
 * 安装类
 */
class Installation
{
    /**
     * 菜单KEY
     */
    const MENU_KEY = 'management_center';

    /**
     * 安装方法
     * @param string $version
     * @return void
     */
    public static function install(string $version = ''): void
    {
        // 安装应用插件和数据库
        if (empty(Util::schema()->hasTable('cn_client'))) {
            self::importSqlFile(__DIR__ . '/iyuuplus.sql');
            CrontabInstall::install();
            EmailInstall::install();
            SmsInstall::install();
        }

        // 安装菜单
        if (!Menu::get(self::MENU_KEY)) {
            Menu::import(include __DIR__ . '/menu.php');
        }
    }

    /**
     * 导入SQL文件
     * @param string $sqlFilePath
     * @return void
     */
    public static function importSqlFile(string $sqlFilePath): void
    {
        if (!file_exists($sqlFilePath)) {
            throw new InvalidArgumentException('sql文件不存在');
        }

        try {
            //读取.sql文件内容
            $sqlContent = file($sqlFilePath);

            $tmp = '';
            // 执行每个SQL语句
            foreach ($sqlContent as $line) {
                if (trim($line) == '' || stripos(trim($line), '--') === 0 || stripos(trim($line), '/*') === 0) {
                    continue;
                }

                $tmp .= $line;
                if (str_ends_with(trim($line), ';')) {
                    $tmp = str_ireplace('INSERT INTO', 'INSERT IGNORE INTO', $tmp);
                    Util::db()->statement($tmp);
                    $tmp = '';
                }
            }
        } catch (Throwable $e) {
            throw new RuntimeException('导入数据库失败：' . $e->getMessage());
        }
    }

    /**
     * 初始化数据
     * @return void
     */
    public static function initDatabase(): void
    {
        if (Util::schema()->hasTable('cn_sites') && !Site::exists()) {
            SitesServices::sync();
        }
    }

    /**
     * 初始化配置文件
     * @return void
     */
    public static function initConfig(): void
    {
        // .env
        // webman/push
        // google2fa
    }

    /**
     * 卸载方法
     * @param string $version
     * @return void
     */
    public static function uninstall(string $version = ''): void
    {
    }
}
